<?php
/**
 * 共用方法
 * Common.php
 * ==============================================
 * 版权所有 2013-2014
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * ----------------------------------------------
 * 
 * @package xcs
 * @author huangdaohai <huangdaohai.2007@163.com>
 * @version V1.0
 * @access public
 */
class Common extends CApplicationComponent {
	/**
	 * Common::getFirstChar() 取得一个字的首字母
	 * 
	 * @param mixed $s0 字符
	 * @return string 字的首字母
	 */
	public function getFirstChar($s0){
		$fchar = ord($s0{0});     
		if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});     
		@$s1 = iconv("UTF-8","gb2312", $s0);     
		@$s2 = iconv("gb2312","UTF-8", $s1);     
		if($s2 == $s0){$s = $s1;}else{$s = $s0;}     
		$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;     
		if($asc >= -20319 and $asc <= -20284) return "A";     
		if($asc >= -20283 and $asc <= -19776) return "B";     
		if($asc >= -19775 and $asc <= -19219) return "C";     
		if($asc >= -19218 and $asc <= -18711) return "D";     
		if($asc >= -18710 and $asc <= -18527) return "E";     
		if($asc >= -18526 and $asc <= -18240) return "F";     
		if($asc >= -18239 and $asc <= -17923) return "G";   
		if($asc >= -17922 and $asc <= -17418) return "H";     
		if($asc >= -17417 and $asc <= -16475) return "J";     
		if($asc >= -16474 and $asc <= -16213) return "K";     
		if($asc >= -16212 and $asc <= -15641) return "L";     
		if($asc >= -15640 and $asc <= -15166) return "M";     
		if($asc >= -15165 and $asc <= -14923) return "N";     
		if($asc >= -14922 and $asc <= -14915) return "O";     
		if($asc >= -14914 and $asc <= -14631) return "P";     
		if($asc >= -14630 and $asc <= -14150) return "Q";     
		if($asc >= -14149 and $asc <= -14091) return "R";     
		if($asc >= -14090 and $asc <= -13319) return "S";     
		if($asc >= -13318 and $asc <= -12839) return "T";     
		if($asc >= -12838 and $asc <= -12557) return "W";     
		if($asc >= -12556 and $asc <= -11848) return "X";     
		if($asc >= -11847 and $asc <= -11056) return "Y";     
		if($asc >= -11055 and $asc <= -10247) return "Z";     
		return null; 
	}  
	/**
	 * Common::getMoreFirstChar() 取得多个连续字的首字母
	 * 
	 * @param string $zh 需要取得字母的字符串
	 * @return string 字对应的字母串
	 */
	public function getMoreFirstChar($zh){     
		$ret = "";     
		@$s1 = iconv("UTF-8","gb2312", $zh);     
		@$s2 = iconv("gb2312","UTF-8", $s1);     
		if($s2 == $zh){$zh = $s1;}  
		for($i = 0; $i < strlen($zh); $i++){         
			$s1 = substr($zh,$i,1);         
			$p = ord($s1); 
			if($p > 160){             
				$s2 = substr($zh,$i++,2);             
				$ret .= self::getFirstChar($s2);         
			}else{             
				$ret .= $s1;         
			}     
		}

		return $ret; 
	}
    /**
     * Common::getIp() 获取客户端IP
     * 
     * @return string 客户端IP字符串
     */
    public function getIp() {
		if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" )) {
			$ip = getenv ( "HTTP_CLIENT_IP" );
		} elseif (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" )) {
			$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
		} elseif (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" )) {
			$ip = getenv ( "REMOTE_ADDR" );
		} elseif (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" )) {
			$ip = $_SERVER ['REMOTE_ADDR'];
		} else {
			$ip = "unknown";
		}
		return $ip;
	}
    /**
     * 获取文件后缀
     * @param unknown_type $file 文件名或者文件url
     * @return mixed 后缀
     */
    public function getFilePostfix($file){
        $afile=explode('.', $file);
        $postfix=end($afile);
        // || !in_array($postfix, array('jpg','jpeg','png','gif')
        if( empty( $postfix )) {
        	$postfix='';
        }
        return strtolower($postfix);
    }
    public function getFileName($file){
        $afile=explode('/', $file);
        $postfix=end($afile);
        // || !in_array($postfix, array('jpg','jpeg','png','gif')
        if( empty( $postfix )) {
        	$postfix='';
        }
        return strtolower($postfix);
    }
    /**
     * 生成本地指定文件夹下的相对路径（带文件名）
     * @param unknown_type $postfix 后缀
     * @return string 返回带文件名的相对路径
     */
    public function getPathFileName($postfix=''){
        if( empty( $postfix ) ) return $savePath;
        //新生成的文件名
        $filename=Yii::app()->user->id."_".time().Yii::app()->common->randCode(4).'.'.$postfix;
        
        //在指定的文件夹下要创建的子文件夹路径
        $modtype=isset($_POST['modtype'])?trim($_POST['modtype']):'';
        if($modtype){
            $savePath=$modtype.'/'.date('Y').'/'.date('m').'/'.date('d');
        }else{
            $savePath=date('Y').'/'.date('m').'/'.date('d');
        }
        $asavePath = explode('/', $savePath);
        
        if(Yii::app()->params['upload']['ftpenable']){
            $ftp = Yii::app()->ftp;
            $ftp->chdir('/');
            //在ftp服务器上生成文件夹
            foreach ($asavePath as $v){
                if(!@$ftp->chdir($v)){
                    $ftp->mkdir($v);
                    $ftp->chdir($v);
                }
            }
        }else{
            //在本地生成文件夹
            $saveLocalPath=Yii::app()->params['upload']['uploadlocal'];
            foreach ($asavePath as $v){
                $saveLocalPath.=$v.'/';
                if(!file_exists($saveLocalPath)){
                    mkdir($saveLocalPath);
                }
            }
        }
        return $savePath.'/'.$filename;
    }    
	/**
	 * 生成指定位数的字母随机码
	 *
	 * @return 随机码
	 * @authoer ljc
	 */
	public static function randCode($length=4,$isNum=''){
		$randCode = '';
		if($isNum){
			$chars = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ); 
			$charsLen = count($chars) - 1; 
			for ($i=0;$i<$length;$i++) 
			{
				$randCode.=$chars[mt_rand(0, $charsLen)];
			}
		}else{
			for ($i=0;$i<$length;$i++) 
			{
				$randCode.=chr(mt_rand(97, 122));
			}
		}
		return $randCode;
	}
    /**
     * 传入相关文件保存到本地或者FTP服务器上
     * @param array $attributes
     * @return array 属性
     */
    public function saveFile($attributes){
        $attributes['status']=1;
        $imagesize = @getimagesize($attributes['filepath']);
        $attributes['filetype']=isset($imagesize['mime'])?$imagesize['mime']:'';
        
        $model = new BaseAttachmentModel();
        $model->uid=isset(Yii::app()->user->id)?Yii::app()->user->id:0;
        $model->postip=Yii::app()->common->getIp();
        $model->filename=$attributes['filename'];
        $model->size=$attributes['filesize'];
        $model->type=$attributes['filetype'];
        $model->extensionname=$attributes['extensionName'];
        $model->filepath=$attributes['filepath'];
        $model->serverpath=$attributes['serverpath'];
        $model->width=isset($imagesize[0])?$imagesize[0]:0;
        $model->height=isset($imagesize[1])?$imagesize[1]:0;
        $model->modtype=isset($attributes['modtype']) && !empty($attributes['modtype'])?$attributes['modtype']:'default';
        $model->isuse=0;
        $model->dateline=time();
        $model->location=$attributes['location'];
        $model->save();
        $return = array(
                'status'=>$attributes['status'],
                'aid'=>$model->aid,
                'oldname'=>str_replace('.'.$model->extensionname, '', $attributes['oldName']),
                'filename'=>$model->filename,
                'serverpath'=>$model->serverpath,
                'url'=>$model->filepath,
                'width'=>$model->width,
                'height'=>$model->height,
                'size'=>$model->size,
                'type'=>$model->type,
                'extensionname'=>$model->extensionname
                );
        return $return;
    }    
    /**
     * Common::formattime()  格式化时间
     * 
     * @param mixed $format  格式化规则
     * @param mixed $time 需要格式时间戳时间
     * @param string $emptystring  $time 为空是显示的字符
     * @return string 格式化后的时间字符
     */
    public function formattime($format ,$time ,$emptystring=''){
        if( empty( $time ) ){
            return $emptystring;
        }
        return date($format ,$time);
    }
    /**
     * Common::formatnumber() 格式化数字
     * 
     * @param mixed $floatnumber 格式化数
     * @param mixed $decimals 小数点位数
     * @param string $prefix 格式化后前缀
     * @return string 格式化后的字符
     */
    public function formatnumber($floatnumber ,$decimals ,$prefix=''){
        if( empty( $floatnumber ) ){
            return $prefix . number_format(0,$decimals);
        }
        return $prefix . number_format($floatnumber ,$decimals);
        
    }
    /**
    * Common::string2array()将字符串转换为数组
    *
    * @param	string	$data	字符串
    * @return	array	返回数组格式，如果，data为空，则返回空数组
    */
    function string2array($data) {
        $array = array();
    	if($data == '') return array();
    	eval("\$array = $data;");
    	return $array;
    }
    /**
    * 将数组转换为字符串
    *
    * @param	array	$data		数组
    * @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
    * @return	string	返回字符串，如果，data为空，则返回空
    */
    function array2string($data, $isformdata = 0) {
    	if($data == '') return '';
    	if($isformdata) $data = $this->new_stripslashes($data);
    	return var_export($data, TRUE);
    }
    /**
     * 返回经stripslashes处理过的字符串或数组
     * @param $string 需要处理的字符串或数组
     * @return mixed
     */
    function new_stripslashes($string) {
    	if(!is_array($string)) return stripslashes($string);
    	foreach($string as $key => $val) $string[$key] = $this->new_stripslashes($val);
    	return $string;
    }
    /**
     * 返回经htmlspecialchars处理过的字符串或数组
     * @param $obj 需要处理的字符串或数组
     * @return mixed
     */
    function new_html_special_chars($string) {
    	$encoding = 'utf-8';
    	if(strtolower(Yii::app()->db->charset)=='gbk') $encoding = 'gb2312';
    	if(!is_array($string)) return htmlspecialchars($string,ENT_QUOTES,$encoding);
    	foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
    	return $string;
    }
}
?>